from robot.api import logger
from robotlibcore import keyword

from robot.utils.asserts import assert_true

import requests
import json
from RequestsLogger import write_log
from .JsonSchemaLib import JsonSchemaLib

class HttpLibrary(object):

    def __init__(self):
        self.schema = JsonSchemaLib()

    @keyword('Http Get')
    def http_get(self, host, uri, post_data, headerType="", cookies=""):
        """
        通用http请求-GET0
        """
        logger.info("[Http请求] 测试接口url: {0}".format(host + uri))
        logger.info("[Http请求] 测试接口参数为 {0}".format(post_data))
        logger.info("[Http请求] 测试接口header为 {0}".format(headers))

        s = requests.Session()
        
        if headerType.lower() == "query":
            http_resp = s.get(url=(host + uri), params=post_data, cookies=cookies)
            logger.info("url: {}".format(http_resp.url))
        
        elif headerType.lower() == "json":
            http_resp = s.get(url=(host + uri), data=json.dumps(post_data), headers={'Content-Type': 'application/json'}, cookies=cookies)
        
        elif headerType.lower() == "form":
            http_resp = s.get(url=(host + uri), data=post_data, headers={'Content-Type': 'application/x-www-form-urlencoded'}, cookies=cookies)
        
        write_log(http_resp)
        s.close()

        data = json.loads(http_resp.content)

        self.schema.create_schema(data)
        
        return data
         
    
    @keyword('Http Post')
    def http_post(self, host, uri, post_data, headerType="", cookies=""):
        """
        通用http请求-Post
        """
        logger.info("[Http请求] 测试接口url: {0}".format(host + uri))
        logger.info("[Http请求] 测试接口参数为 {0}".format(post_data))
        logger.info("[Http请求] 测试接口header为 {0}".format(headerType))

        s = requests.Session()

        if headerType.lower() == "query":
            http_resp = s.post(url=(host + uri), params=post_data, cookies=cookies)
            logger.info("url: {}".format(http_resp.url))

        elif headerType.lower() == "json":
            http_resp = s.post(url=(host + uri), data=json.dumps(post_data), headers={'Content-Type': 'application/json'}, cookies=cookies)
        
        elif headerType.lower() == "form":
            http_resp = s.post(url=(host + uri), data=post_data, headers={'Content-Type': 'application/x-www-form-urlencoded'}, cookies=cookies)
        
        write_log(http_resp)
        s.close()
        data = json.loads(http_resp.content)

        self.schema.create_schema(data)
        
        return data
        
    
    @keyword('Get Http Cookie')
    def get_http_cookie(self, host, uri, loginUser, cookieName="sso-epctoken"):
        
        logger.info("[Cookie获取] 登录者: {}".format(loginUser))
        loginUser = {"loginName": loginUser, "password": "a5eGNsovdGY=", "rememberMe": "false"}

        s = requests.Session()
        http_resp = s.post(url=(host + uri), data=loginUser, headers={'Content-Type': 'application/x-www-form-urlencoded'}) 
        s.close()

        # write_log(http_resp)
        cookies = http_resp.cookies.items()
        cookie = {}

        for name, value in cookies:
            if name == cookieName:
                cookie[cookieName] = value
        
        logger.info("[Cookie获取] 结果为: {}".format(cookie))
        assert_true(any(cookie), "cookie不能为空")

        return cookie